package com.talent.codes.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import com.freewayso.image.combiner.ImageCombiner;
import com.freewayso.image.combiner.element.RectangleElement;
import com.freewayso.image.combiner.enums.OutputFormat;
import com.itextpdf.io.image.ImageData;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;

import com.talent.codes.model.GasIdCtrl;
import com.talent.codes.model.PrintSetting;
import com.talent.codes.model.GasLabel;

/**
 * 一般画图用的是像素， 每英寸的像素个数为96
 */
public class GasLabelGenerator {
    private static final double _DPI=300.0;

    public static void saveToPdf(String pdfPath, String imagePath) throws Exception {
        // 读取图片
        ImageData imageData = ImageDataFactory.create(imagePath);
        float imageWidth = imageData.getWidth();
        float imageHeight = imageData.getHeight();

        // 创建PDF文档
        PdfWriter writer = new PdfWriter(pdfPath);
        PdfDocument pdfDoc = new PdfDocument(writer);
        Document document = new Document(pdfDoc, new PageSize(imageWidth, imageHeight));

        // 添加图片到PDF
        com.itextpdf.layout.element.Image image = new com.itextpdf.layout.element.Image(imageData);
        // 如果需要，可以设置图片的位置和大小，但在这里我们让图片填充整个页面
        // image.setFixedPosition(x, y); // 设置图片的绝对位置（可选）
        // image.scaleToFit(width, height); // 缩放图片到指定大小（可选）

        // 由于我们已经根据图片大小设置了页面大小，所以这里不需要缩放图片
        // 直接将图片添加到文档中即可
        document.add(image);

        // 关闭文档
        document.close();
    }

    public static RectangleElement addRectangleElement(ImageCombiner combiner, int x, int y, int width, int height) {
        RectangleElement rectangleElement = new RectangleElement(x, y, width, height);
        rectangleElement.setColor(Color.BLACK);
        combiner.addElement(rectangleElement);
        return rectangleElement;
    }
    public static void writeToImage(String imgPath, GasLabel label, PrintSetting page) throws Exception {
        byte[] bytes = writeToImage(label,page);

        try(FileOutputStream file = new FileOutputStream(imgPath)){
            file.write(bytes);
        }
    }

    public static byte[] writeToImage(GasLabel label, PrintSetting page) throws Exception {

        GasIdCtrl idCtrl = new GasIdCtrl(label, page.getFirstId(), page.getIdCnt());
        int pageWidth = page.pageWidth();
        int pageHeight = page.pageHeight();
        int columns = page.getColumns();
        int lines = page.pageLines();

        int marginH = page.getMarginH();
        int marginV = page.getMarginV();
        int boxWidth = page.boxWidth();
        int boxHeight =  page.boxHeight();
        int boxPadding = page.boxPadding();

        ImageCombiner combiner = new ImageCombiner(pageWidth, pageHeight, Color.WHITE, OutputFormat.JPG);  //v1.1.4之后可以指定背景图新宽高了（不指定则默认用图片原宽高）
        combiner.setQuality(1.0f);

        if(page.isDividerV()) {
            for (int iCol = 0; iCol < page.getColumns() + 1; iCol++) {
                int xx = marginH + iCol * boxWidth;
                addRectangleElement(combiner, xx, marginV, 2, pageHeight - marginV * 2);
                //.setGradient(Color.gray, Color.red, GradientDirection.TopBottom).setAlpha(.3f);  //渐变遮罩
            }
        }

        if(page.isDividerH()) {
            for (int iRow = 0; iRow < lines + 1; iRow++) {
                int yy = marginV + iRow * boxHeight;
                addRectangleElement(combiner, marginH, yy, pageWidth - marginH * 2, 2);
                //.setGradient(Color.gray, Color.red, GradientDirection.TopBottom).setAlpha(.3f);  //渐变遮罩
            }
        }


        for (int iRow = 0; iRow < lines; iRow++) {
            int y = marginV + boxPadding + boxHeight * iRow;

            for (int iCol = 0; iCol < columns; iCol++) {
                //看看是否是空位
                if(page.isEmptyBox(iRow, iCol)) continue;
                if(!idCtrl.hasNext()) break;

                idCtrl.next();

                byte[] imgData = idCtrl.curLabelData();
                BufferedImage img = ImageIO.read(new ByteArrayInputStream(imgData));
                int x = marginH + boxPadding + boxWidth * iCol;
                combiner.addImageElement( img, x, y);
            }
        }
        combiner.combine();

        try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            os.write(combiner.getCombinedImageStream().readAllBytes());
            return os.toByteArray();
        }
    }

//    public static void writeToPdf(String pdfPath, GasLabel label, PrintSetting page) throws Exception {
//        Path path = Paths.get(pdfPath).getParent().toString();
//        String imgPath =  path + File.separator + "";
//        writeToImage(imgPath, label, page);
//        saveToPdf(pdfPath, imgPath);
//    }

    public static byte[] resizeImage(byte[] imgBytes, int widthInches, int heightInches) throws IOException{
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(new ByteArrayInputStream(imgBytes));
        // 计算目标像素尺寸
        int widthPixels = (int) (widthInches * _DPI);
        int heightPixels = (int) (heightInches * _DPI);
        BufferedImage resizedImage = new BufferedImage(widthPixels, heightPixels, originalImage.getType());

        Graphics2D g = resizedImage.createGraphics();
        g.drawImage(originalImage, 0, 0, widthPixels, heightPixels, null);
        g.dispose();
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(resizedImage, "png", os);
        return os.toByteArray();
    }
}
